package com.easywork.mystery.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easycore.utils.BaseController;
import com.easycore.utils.JwtUtils;
import com.easywork.mystery.entity.MsgComm;
import com.easywork.mystery.entity.SysUser;
import com.easywork.mystery.rpc.DemoService;
import com.easywork.mystery.service.MsgCommService;

@Controller
@RequestMapping("/mona/MsgComm")
public class MsgCommController extends BaseController {
	@Autowired
	private MsgCommService msgcommService;

	@Autowired
	private DemoService demoService;

	// --发邮件
	@RequestMapping("/sendMail")
	@ResponseBody
	public String sendMail(HttpServletRequest req, String receiver, String title, String content) {
		if (receiver == null || "".equals(receiver)) {
			return "收件人不能为空";
		}
		if (title == null || "".equals(title)) {
			title = "(空主题)";
		}
		if (content == null || "".equals(content)) {
			return "正文内容不能为空";
		}
		String user_s = super.getCookieVal(req, "ssotoken");
		SysUser userSend = JwtUtils.getObject(user_s, SysUser.class);
		SysUser userRecevier = demoService.getSysUserByAccount(receiver, user_s);
		// --检查是否匹配数据库的收件人
		if (userRecevier == null) {
			return "没有该收件人,请确认收件人信息";
		}
		msgcommService.saveMail(userSend, userRecevier, title, content);
		return "success";
	}

	// --查看所有邮件
	@RequestMapping("/findAll")
	@ResponseBody
	public Page<MsgComm> findAll(HttpServletRequest req, Integer pageNum, Integer pageSize) {
		String user_s = super.getCookieVal(req, "ssotoken");
		SysUser user = JwtUtils.getObject(user_s, SysUser.class);
		Sort sort = new Sort(Sort.Direction.DESC, "createtime");
		Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
		return msgcommService.findAll(user, pageable);
	}

	// -- 改已读为未读
	@RequestMapping("/changeFlag")
	@ResponseBody
	public String changeFlag(Long changeId) {
		MsgComm msgComm = msgcommService.findById(changeId);
		msgComm.setReadflag(0);
		msgcommService.saveMsgComm(msgComm);
		return "success";
	}

	// --删除所有邮件
	@RequestMapping("/delAll")
	public String delAll(HttpServletRequest req) {
		String user_s = super.getCookieVal(req, "ssotoken");
		SysUser user = JwtUtils.getObject(user_s, SysUser.class);
		msgcommService.deleteAll(user);
		return "/demo/receiver";
	}
}